package main.java.employee;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * Author: Tristan
 * Date: 2023/6/25 16:13
 */
public class SalaryCaculator {

    public void calcSalaryAfterTax(List<EmployeeSalary> salaryList, List<TaxTable> taxTable) {
        // 请填写计算方法，将税后工资计算结果放到salaryAfterTax字段中

        // taxTable 排序，使得税率从小到大
        taxTable.sort(Comparator.comparingInt(TaxTable::getLevel));


        for (EmployeeSalary employee: salaryList) {

            String salary = employee.getSalary();

            double amt = 0;
            try {
                amt = Double.parseDouble(salary);

            } catch (NumberFormatException e) {
                e.printStackTrace();
                // 数值异常
            }

            if (amt < 0) {
                // 薪水值异常
                continue;
            }

            // 交税总额
            BigDecimal total = BigDecimal.ZERO;

            // 工资计税拆分
            for (TaxTable tax : taxTable) {

                // 分层交税部分
                boolean overflow = amt > tax.getUpper().doubleValue();
                if (overflow) {  // 超过该阶梯，取最大税额

                    total = total.add(tax.getMaxTaxValue());

                } else { // 不超过该阶梯， 取实际计税， 并结束

                    total = total.add(BigDecimal.valueOf(amt).subtract(tax.getLower()).multiply(tax.getRate()));

                    break;

                }


            }

            // 税后
            BigDecimal afterTax = BigDecimal.valueOf(amt).subtract(total);

            employee.setSalaryAfterTax(afterTax.toString());

            System.out.println(employee);



        }



    }



    // 生成测试
    private static List<TaxTable> getTaxTable(){

        TaxTable level1 = new TaxTable(1, 1, BigDecimal.valueOf(0), BigDecimal.valueOf(1000), BigDecimal.valueOf(0));
        TaxTable level2 = new TaxTable(1, 1, BigDecimal.valueOf(1000), BigDecimal.valueOf(10000), BigDecimal.valueOf(0.1));
        TaxTable level3 = new TaxTable(1, 1, BigDecimal.valueOf(10000), BigDecimal.valueOf(20000), BigDecimal.valueOf(0.2));
        TaxTable level4 = new TaxTable(1, 1, BigDecimal.valueOf(20000), BigDecimal.valueOf(Long.MAX_VALUE), BigDecimal.valueOf(0.3));


        return Arrays.asList(level1, level2, level3, level4);

    }


    private static List<EmployeeSalary> getEmployee() {
        EmployeeSalary tony1 = new EmployeeSalary(1L, "Tony", "15000");
        EmployeeSalary tony2 = new EmployeeSalary(2L, "Po", "21300");
        EmployeeSalary tony3 = new EmployeeSalary(3L, "Ty", "10800");
        EmployeeSalary tony4 = new EmployeeSalary(3L, "Pam", "300");

        return Arrays.asList(tony1, tony2, tony3, tony4);
    }

    public static void main(String[] args) {


        SalaryCaculator calc = new SalaryCaculator();
        calc.calcSalaryAfterTax(getEmployee(), getTaxTable());



    }
}
